
/** 单词标记 */
const useWordMarker = () => {
	/** 替换字符串 */
	const replaceString = (list: Record<string, any>[], word: string) => {
		let index = 0;
		let bool = false;
		
		return (() => list.reduce((str, newItem, newIndex) => {
			index = bool ? index + newItem.value.length - newItem.key.length : index;
			bool = true;
			return `${str.slice(0, index + newIndex)}${newItem.value}${str.slice(index + newIndex + newItem.key.length)}`;
			
		}, word))();
	};
	
	/** 查找相同的 */
	const findTheSame = (list: Record<string, any>[], word: string, value: string) => {
		if (word.includes(value)) {
			const newItem = { key: value, value: `<span style="color: #FF5252">${value}</span>` };
			const indexOf = word.indexOf(value);
			if (!list[indexOf] && !(list[indexOf + 1] && value.length > 1)) list[indexOf] = newItem;
			let indexTotal = indexOf;
			
			/** 查找相同的辅助函数 */
			const _findTheSame = (index: number) => {
				const newStr = word.slice(index + value.length);
				if (!newStr) return;
				const lastIndexOf = newStr.indexOf(value);
				if (!!~lastIndexOf) {
					indexTotal += lastIndexOf + 1;
					if (!!list.find((item, index) => item?.key.includes(value) && item.key !== value && index < indexTotal)) _findTheSame(indexTotal);
					else list[indexTotal] = newItem;
				};
			};
			
			_findTheSame(indexTotal);
		};
	};
	
	
	return {
		/**
		 * @description 标记
		 * @param { Record<string, unknown>[] } list 标记列表
		 * @param { string } word 要标记的字符串
		 * @param { number } index 索引
		 */
		markers: (list: string[], word: string, index: number) => {
			if (word.endsWith('</div>')) return word;
			const words = [];
			list?.forEach?.(marker => {
				findTheSame(words, word, marker);
			});
			
			return `<div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap">${replaceString(words, word)}</div>`;
		},
		
		/**
		 * @description 标记
		 * @param { Record<string, unknown>[] } list 标记列表
		 * @param { string } word 要标记的字符串
		 * @param { number } index 索引
		 */
		clearMark: (list: string[], word: string, index: number) => {
			list?.forEach?.(marker => {
				word = word?.replace(new RegExp(`<span style="color: #FF5252">${marker}</span>`, 'g'), marker);
			});
			
			return word
				?.replace?.('<div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap">', '')
				?.replace?.('</div>', '')
		}
	}
};


export default useWordMarker;